package com.itech.stocks;

import java.text.MessageFormat;

import com.itech.util.UtilHttp;

public class Utils {
	private static final String QOUTE_URL = "http://getquote.icicidirect.com/" +
	"trading/equity/trading_stock_quote.asp?Symbol={0}";
	private static final String FNO_URL = "https://secure.icicidirect.com/trading/fno/GetQuote.asp?" +
	"FFO_UNDRLYNG={0}&FFO_XCHNG_CD=NFO&FFO_PRDCT_TYP=O&FFO_OPT_TYP={1}&" +
	"FFO_EXPRY_DT={2}&FFO_EXER_TYP={4}&FFO_RQST_TYP=*&FFO_STRK_PRC={3}";
	//{0} - Symbol. Unitec
	//{1} - type P/C
	//{2} - expiry date 27-Aug-2009
	//{3} - STRIKE price - 8000
	//{4} - index type A(equity)/E(index)

	private static final String LAST_TRADE_LINE = "PRICE</TD>";
	private static final String DAY_OPEN = "OPEN</TD>";
	private static final String DAY_HIGH = "HIGH</TD>";
	private static final String DAY_LOW = "LOW</TD>";
	private static final String PREVIOUS_DAY_CLOSE = "CLOSE</TD>";


	private static final String QOUTE_URL_START_YAHOO = "http://in.finance.yahoo.com/d/quotes.csv?s=";
	private static final String QOUTE_URL_END_YAHOO = ".NS&f=sl1d1t1c1ohgv";
	private final UtilHttp utilHttp = new UtilHttp(10);


	public double getLastPriceFromYahooF(String symbol) {
		String finalURL = QOUTE_URL_START_YAHOO + symbol + QOUTE_URL_END_YAHOO;
		String response = utilHttp.getHttpResponse(finalURL);
		if (response == null) {
			throw new NullPointerException("Response can not be found for symbol: " + symbol + ".");
		}
		String[] parsed = response.split(",");
		if (parsed[0].contains(symbol)) {
			return Double.parseDouble(parsed[1]);
		} else{
			throw new RuntimeException("Invalid Response for symbol: " + symbol + ".");
		}
	}
	public double getLastTradePrice(String symbol) {
		String finalURL = QOUTE_URL + symbol;
		String response = utilHttp.getHttpResponse(finalURL);
		if (response == null) {
			throw new NullPointerException("Response can not be found for symbol: " + symbol + ".");
		}
		response = response.replace("\n", "");
		response = response.replace("\r", "");
		response = response.replace("\t", "");
		int startIndex = response.indexOf(">", (response.indexOf(LAST_TRADE_LINE) + LAST_TRADE_LINE.length()));
		int endIndex = response.indexOf("<", startIndex);
		String result = response.substring(startIndex + 1, endIndex);
		result = result.replaceAll(",", "");
		return Double.parseDouble(result);
	}

	private double getPriceFromResponse(String response, String priceType) {
		int startIndex = response.indexOf(">", (response.indexOf(priceType) + priceType.length()));
		int endIndex = response.indexOf("<", startIndex);
		String result = response.substring(startIndex + 1, endIndex);
		result = result.replaceAll(",", "");
		return Double.parseDouble(result);
	}

	public StockPrice getStockPriceFor(Stock stock) {
		try {
			String finalURL = "";
			if (Stock.Type.FNO.equals(stock.getType())) {
				String indexType = Stock.IndexType.INDEX.equals(stock.getIndexType()) ? "E" : "A";
				String[] args = new String[] {stock.getSymbol(), stock.getFnoType(), stock.getExpiryDate(),
						stock.getStrikePrice(), indexType};
				finalURL = MessageFormat.format(FNO_URL, args);
			} else {
				String[] args = new String[] {stock.getSymbol()};
				finalURL = MessageFormat.format(QOUTE_URL, args);
			}
			String response = utilHttp.getHttpResponse(finalURL);
			if (response == null) {
				throw new NullPointerException("Response can not be found for symbol: " + stock.getSymbol() + ".");
			}
			response = response.replace("\n", "");
			response = response.replace("\r", "");
			response = response.replace("\t", "");
			response = response.replace("&nbsp;", "");
			response = response.replace(" <", "<");
			response = response.replace("\t<", "<");
			response = response.toUpperCase();
			StockPrice stockPrice = new StockPrice();
			stockPrice.setSymbol(stock.getSymbol());

			stockPrice.setDayHigh(getPriceFromResponse(response, DAY_HIGH));
			stockPrice.setDayLow(getPriceFromResponse(response, DAY_LOW));
			stockPrice.setLastTradePrice(getPriceFromResponse(response, LAST_TRADE_LINE));
			stockPrice.setDayOpen(getPriceFromResponse(response, DAY_OPEN));
			stockPrice.setPreviousDayClose(getPriceFromResponse(response, PREVIOUS_DAY_CLOSE));
			return stockPrice;
		} catch (Exception e) {
			System.out.println("Unable to get proper response for stock - " + stock.getSymbol());
			return null;
		}
	}
}
